package com.isyscore.os.metadata.controller;

import cn.hutool.core.collection.CollUtil;
import com.google.common.collect.Lists;
import com.isyscore.boot.login.LoginUserManager;
import com.isyscore.device.common.model.RespDTO;
import com.isyscore.device.common.util.JsonMapper;
import com.isyscore.os.core.model.dto.LicenseQueryDTO;
import com.isyscore.os.core.model.enums.LicenseEnable;
import com.isyscore.os.core.model.enums.LicenseOption;
import com.isyscore.os.metadata.config.LicenseLimitSupport;
import com.isyscore.os.metadata.manager.QuartzJobManager;
import com.isyscore.os.metadata.service.DataFlowDefinitionService;
import com.isyscore.os.metadata.service.LicenseService;
import com.isyscore.os.metadata.service.impl.MetricJobService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.List;

import static com.isyscore.os.metadata.constant.CommonConstant.DEPLOY_MODE_STANDALONE;

@RestController
@RequestMapping("${api-full-prefix}/masterSlaveSwitcher")
@Api(tags = "master-slave切换")
@Slf4j
public class MasterSlaveSwitcherController {
    @Value("${service.license.check:true}")
    private Boolean enableLicenseCheck;
    @Autowired
    private MetricJobService metricJobService;
    @Autowired
    private LicenseLimitSupport licenseLimitSupport;
    @Autowired
    private DataFlowDefinitionService dataFlowDefinitionService;

    @Autowired
    private QuartzJobManager quartzJobManager;

    @Autowired
    private LicenseService licenseService;
    @Autowired
    private LoginUserManager loginUserManager;


    private String currentRole = "slave";

    @Value("${metadata.deploy-mode}")
    private String deployMode = DEPLOY_MODE_STANDALONE;

    @PostConstruct
    public void init() throws Exception {
        if (deployMode.equalsIgnoreCase(DEPLOY_MODE_STANDALONE)) {
            this.switch2Master();
        }
        log.info("当前的服务的角色为：" + currentRole);
    }

    @ApiOperation("（内部API）切换当前服务为master")
    @PutMapping("/master")
    public RespDTO<?> switch2Master() throws Exception {
        licenseCheck();
        this.currentRole = "master";
        quartzJobManager.stopAllMetricJob();
        metricJobService.startAllMetricJobFromDatabase();
        dataFlowDefinitionService.startAllDataJobFromDatabase();
        return RespDTO.onSuc();
    }

    @ApiOperation("（内部API）切换当前服务为slave")
    @PutMapping("/slave")
    public RespDTO<?> switch2Slave() {
        this.currentRole = "slave";
        quartzJobManager.stopAllMetricJob();
        return RespDTO.onSuc();
    }

    @ApiOperation("（内部API）查看当前服务的角色")
    @GetMapping("/role")
    public RespDTO<String> getRole() {
        return RespDTO.onSuc(this.currentRole);
    }

    public void licenseCheck() {
        boolean check = Boolean.FALSE;
        boolean licenseCheck = enableLicenseCheck;
        Integer dataSourceQuantity = 0;
        try {
            LicenseQueryDTO dto = LicenseQueryDTO.builder().ids(Lists.newArrayList(LicenseOption.UDMP_ENABLE.getCode(), LicenseOption.DATASOURCE_QUANTITY.getCode())).build();
            RespDTO<List> respDTO = licenseService.query(dto);
            log.info("license查询返回信息：{}", JsonMapper.toAlwaysJson(respDTO));
            List licenseResp = respDTO.getData();
            if (CollUtil.isNotEmpty(licenseResp) && licenseResp.size() == 2) {
                Integer udmpEnable = (Integer) licenseResp.get(0);
                if (LicenseEnable.ENABLE.getCode().equals(udmpEnable)||LicenseEnable.NOT_SUPPORT.getCode().equals(udmpEnable)) {
                    log.info("License授权认证成功:UDMP授权状态:{}", udmpEnable);
                    check = true;
                } else {
                    log.error("License授权认证失败:UDMP授权状态:{}", udmpEnable);
                }
                Integer dataSource = (Integer) licenseResp.get(1);
                //如果返回-1,则不限制数据源
                if(LicenseEnable.ENABLE.getCode().equals(dataSource)||LicenseEnable.NOT_SUPPORT.getCode().equals(dataSource)){
                    licenseCheck = false;
                }else {
                    dataSourceQuantity = dataSource;
                }
            } else {
                log.error("License授权认证失败:授权服务返回信息不正确");
            }
        } catch (Exception e) {
            log.error("License授权认证失败:{}", e.getMessage());
            check = getDefaultCheckStatus();
        } finally {
            loginUserManager.setAppLicenseStatus(check);
            licenseLimitSupport.setDataSourceLimit(dataSourceQuantity);
            licenseLimitSupport.setEnableLicenseCheck(licenseCheck);
        }
    }

    /**
     * 获取默认授权
     *
     * @return 如果开启授权检查，返回FALSE，否则返回TRUE
     */
    private Boolean getDefaultCheckStatus() {
        if (enableLicenseCheck) {
            return Boolean.FALSE;
        } else {
            return Boolean.TRUE;
        }
    }
}
